import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:sqflite/sqflite.dart';

import '../constants/constants.dart';
import 'sqflite_helper.dart';
import 'task_entity.dart';

class TaskProvider {
  final _updateTriggerController = StreamController<bool>.broadcast();
  Database? db;

  // 私有构造函数
  TaskProvider._internal() {
    db = SqfliteHelper.instance.db;
  }

  // 静态实例变量
  static final TaskProvider _instance = TaskProvider._internal();

  // 静态工厂方法
  static TaskProvider get instance => _instance;

  static Future createTaskTable(Database db) async {
    await db.execute('DROP TABLE If EXISTS $table');
    await db.execute(
      'CREATE TABLE $table($columnId INTEGER PRIMARY KEY, $columnTaskId TEXT, $columnUrl TEXT,  $columnCreatedAt REAL, $columnProgress REAL, $columnStatus TEXT, $columnFileName TEXT, $columnFilePath TEXT, $columnGroup TEXT , $columnFileSize REAL)',
    );
  }

  ///
  /// 更新
  ///
  /// 更新
  void _triggerUpdate() {
    if (!_updateTriggerController.isClosed) {
      _updateTriggerController.sink.add(true); // 发送通知
    }
  }

  Future<List<TaskEntity>> fetchTaskWithStatus({
    required String status,
  }) async {
    final list = (await db!.query(
      table,
      columns: [
        columnId,
        columnTaskId,
        columnUrl,
        columnFileName,
        columnFileSize,
        columnFilePath,
        columnStatus,
        columnGroup,
        columnCreatedAt,
        columnProgress,
        columnErrorCode,
        columnErrorMessage,
      ],
      where: '$columnStatus = ?',
      whereArgs: <Object?>[status],
      orderBy: '$columnCreatedAt DESC',
      // limit: pageSize,
      // offset: (pageIndex - 1) * pageSize,
    ));
    if (list.isNotEmpty) {
      // final models = BaseModels(list, () => History());
      return list.map((e) => TaskEntity.fromJson(e)).toList();
    }
    return [];
  }

  Future<TaskEntity?> fetchTaskWithId({required String taskId}) async {
    if (db == null) {
      return null;
    }
    final result = (await db!.query(
      table,
      where: '$columnTaskId = ?',
      whereArgs: <Object?>[taskId],
      orderBy: '$columnCreatedAt DESC',
    ))
        .firstOrNull;
    if (result != null) {
      return TaskEntity.fromJson(result);
    }
    return null;
  }

  ///
  /// 根据taskId更新状态
  ///
  Future<int> updateStatusWithTaskId({
    required String taskId,
    required String status,
  }) async {
    if (db == null) {
      return 0;
    }
    final result = await db!.rawUpdate(
        'UPDATE $table SET '
        '$columnStatus = ?, '
        'WHERE $columnTaskId = ?',
        [status, taskId]);
    return result;
  }

  Future<List<TaskEntity>> fetchTaskAll() async {
    final list = await db!
        .rawQuery('SELECT * FROM $table ORDER BY $columnCreatedAt DESC');
    if (list.isNotEmpty) {
      return list.map((e) => TaskEntity.fromJson(e)).toList();
    }
    return [];
  }

  ///
  /// 插入记录
  ///
  insertTask({
    required TaskEntity task,
  }) async {
    if (db == null) {
      return;
    }
    await db!.insert(table, task.toMap());
    _triggerUpdate();
  }

  ///
  /// 更新记录
  ///
  Future<void> updateTask({
    required TaskEntity task,
  }) async {
    if (db == null) {
      return;
    }

    if (task.id == null) {
      await db!.insert(table, task.toMap());
    } else {
      await db!.update(
        table,
        task.toMap(),
        where: '$columnId =?',
        whereArgs: [task.id],
      );
    }
    _triggerUpdate();
  }

  ///
  /// 通过类型移除记录
  ///
  Future<void> deleteWithId({
    required String taskId,
  }) async {
    if (db == null) {
      return;
    }

    await db!.delete(
      table,
      where: '$columnTaskId = ?',
      whereArgs: [taskId],
    );
    _triggerUpdate();
  }

  ///
  /// 监听某类型变化
  ///
  Stream<void> watchTask() {
    late StreamController<void> ctlr;
    StreamSubscription? triggerSubscription;

    ctlr = StreamController<void>(
      onListen: () {
        ctlr.add(null);

        /// Listen for trigger
        triggerSubscription = _updateTriggerController.stream.listen((_) {
          ctlr.add(null);
        });
      },
      onCancel: () {
        triggerSubscription?.cancel();
      },
    );
    return ctlr.stream;
  }

  ///
  /// 监听某类型变化,返回数据
  ///
  /// 监听某类型变化,返回数据
  Stream<List<TaskEntity>> watchTaskWithData({
    required String status,
  }) {
    late StreamController<List<TaskEntity>> ctlr;
    StreamSubscription? triggerSubscription;

    Future<void> sendUpdate() async {
      final tasks = await fetchTaskWithStatus(status: status);
      if (!ctlr.isClosed) {
        debugPrint('sendUpdate: Adding notes to stream');
        ctlr.add(tasks);
      } else {
        debugPrint('sendUpdate: StreamController is closed');
      }
    }

    ctlr = StreamController<List<TaskEntity>>(
      onListen: () async {
        debugPrint('onListen: Starting initial update');
        await sendUpdate();
        debugPrint('onListen: Initial update completed');

        /// Listen for trigger
        triggerSubscription = _updateTriggerController.stream.listen((_) {
          debugPrint('trigger received');
          sendUpdate(); // 接收通知并更新数据
        });
      },
      onCancel: () {
        debugPrint('onCancel: Canceling subscription');
        triggerSubscription?.cancel(); // 取消订阅
      },
    );

    return ctlr.stream;
  }

  /// 清理资源
  void dispose() {
    _updateTriggerController.close();
  }

  Future clearAll() async {
    await db!.delete(table);
    _triggerUpdate();
  }
}
